package com.dingding.activity.core.activity.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dingding.activity.core.activity.dao.ICouponCacheDao;
import com.dingding.activity.core.activity.dao.ICouponCityCacheDao;
import com.dingding.activity.core.activity.dao.ICouponDao;
import com.dingding.activity.core.activity.dao.ICouponGrantRecordCacheDao;
import com.dingding.activity.core.activity.dao.ICouponGrantRecordDao;
import com.dingding.activity.core.activity.service.ICouponService;
import com.dingding.common.core.beans.activity.CouponGrantRecord;
import com.dingding.common.core.beans.activity._Coupon;
import com.dingding.common.core.cache.CacheConstants;
import com.dingding.common.core.cache.base.JedisUtil;
import com.dingding.common.core.cache.enums.DbEnum;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.facade.user.facade.passanger.coupon.IUserCouponFacade;
import com.dingding.facde.activity.enums.ActivityEnum;
import com.dingding.facde.activity.enums.ActivityEnum.CouponStatus;

/**
 * 
 * @Description: 优惠券业务
 * 
 *               优惠券业务必须依赖于活动
 * 
 * @author CHEHUANBO
 * @date 2016年12月6日
 * @version 2.6.2
 * 
 */
@Component("_couponService")
public class CouponServieImpl implements ICouponService {

	private static final Logger log = Logger.getLogger(CouponServieImpl.class);

	@Resource(name = "_couponDao")
	private ICouponDao couponDao;

	@Resource(name = "_couponDao")
	private ICouponCacheDao couponCacheDao;

	@Resource(name = "couponGrantRecordDao")
	private ICouponGrantRecordDao couponGrantRecordDao;

	@Resource(name = "couponGrantRecordDao")
	private ICouponGrantRecordCacheDao couponGrantRecordCacheDao;

	@Resource(name = "couponCityDao")
	private ICouponCityCacheDao couponCityCacheDao;

	@Resource(name = "_couponService")
	private ICouponService couponService;

	@Resource(name = "_userCouponFacade")
	private IUserCouponFacade userCouponFacade;

	/**
	 * 
	 * @Description: 发放优惠券
	 * 
	 *               注意，此功能只能依赖活动发放，不可单独使用
	 * 
	 * @param activityId
	 *            活动ID
	 * @param userId
	 *            用户ID
	 * @return boolean true 成功 false 失败
	 * @author CHEHUANBO
	 * @version V2.6.2
	 * 
	 */
	@Override
	public boolean grantCoupon(String activityId, String userId) {

		if (StringUtils.isBlank(activityId) || StringUtils.isBlank(userId)) {
			throw new NullPointerException("发放优惠券被拒绝，原因：activityId is null or userId is null");
		}

		// 通过活动ID,获取所有活动关联的优惠券
		List<_Coupon> couponList = couponCacheDao.getCouponByActivityIdToCache(activityId);

		if (couponList != null && couponList.size() > 0) {

			for (_Coupon coupon : couponList) {

				// 获取优惠券发放数量
				int couponGrantNumber = coupon.getNumber();
				// 从缓存中获取当前优惠券发放数量
				long isGrantNumber = couponGrantRecordCacheDao
						.getCouponGrantRecordToCacheByCouponId(coupon.getCouponId());
				// 当前优惠券已经发放完毕
				if (couponGrantNumber <= isGrantNumber) {
					continue;
				}

				try {
					boolean isGrant = couponService.isGrantCoupon(userId, activityId);
					if (!isGrant) { // 未领过此券
						// 调用用户服务，给用户添加优惠券
						excuteGrantCoupon(coupon, userId);
						// 添加优惠券发放记录
						addCouponGrantRecord(activityId, userId, coupon.getCouponId());
						continue;
					}

				} catch (Exception e) {
					log.error("发放优惠券出现异常！", e);
					return false;
				}
			}
		}

		return false;

	}

	/**
	 * 
	 * @Description: 执行发放优惠券
	 * @author CHEHUANBO
	 * @version V2.6.2
	 * 
	 */
	private void excuteGrantCoupon(_Coupon coupon, String userId) throws RuntimeException {

		Map<String, Object> queueMap = new HashMap<String, Object>();
		queueMap.put("userId", userId); // 用户ID
		queueMap.put("couponId", coupon.getCouponId()); //优惠券ID
		queueMap.put("faceValue", coupon.getFaceValue()); // 优惠券面值
		queueMap.put("couponType", coupon.getCouponTypeId()); // 优惠券类型
		queueMap.put("useScope", coupon.getUseScope()); // 使用范围
		queueMap.put("startTime", coupon.getStartTime());// 开始时间
		queueMap.put("endTime", coupon.getEndTime());// 结束时间
		queueMap.put("enoughMoney", coupon.getEnoughMoney()); // 满多少钱可以使用
		queueMap.put("maximum", coupon.getMaximum()); // 最高抵扣
		queueMap.put("couponDiscounts", coupon.getCouponDiscounts()); // 折扣
		queueMap.put("cityScope", coupon.getCityScope()); // 城市限制 1:不限制 2:限制

		try {
			userCouponFacade.addUserCoupon(queueMap);
		} catch (Exception e) {
			log.error("调用远程服务添加用户优惠券出现异常！", e);
		}

		// byte[] messageContent = JSONUtil.toJSONString(queueMap).getBytes();
		//
		// Message message = new
		// Message(MessageQueueConfig.getMESSAGE_QUEUE_TOPIC(),
		// QueueTagsConstants.ADD_USER_COUPON,
		// messageContent);

		// SendResult sendResult = ProducerFactory.producer.send(message);

		// log.info("执行发放优惠券,添加消息到队列中：msgId:" + sendResult.getMessageId() +
		// "内容：" + new String(message.getBody()));

	}

	/**
	 * 
	 * @Description:添加优惠券发放记录
	 * @param activityId
	 *            活动ID
	 * @param userId
	 *            用户ID
	 * @param couponId
	 *            优惠券ID
	 * @author CHEHUANBO
	 * @version V2.6.2
	 * 
	 */
	public void addCouponGrantRecord(String activityId, String userId, int couponId) {

		if (StringUtils.isBlank(activityId) || StringUtils.isBlank(userId) || couponId == 0) {
			throw new RuntimeException("添加优惠券发放记录被拒绝！原因：activityId or userId or couponId is null");
		}

		CouponGrantRecord couponGrantRecord = new CouponGrantRecord();
		couponGrantRecord.setCouponId(couponId); // 优惠券ID
		couponGrantRecord.setUserId(userId);// 用户ID
		couponGrantRecord.setActivityId(activityId); // 活动ID

		try {
			couponGrantRecordDao.addCouponGrantRecord(couponGrantRecord);
			String couponGrantRecordKey = CacheConstants.COUPON_GRANT_RECORD_LIST_ + couponId;
			JedisUtil.lpush(couponGrantRecordKey, JSONUtil.toJSONString(couponGrantRecord),
					DbEnum.ActivityDb.getValue());
		} catch (Exception e) {
			log.error("添加优惠券发放记录出现异常！", e);
		}

	}

	/**
	 * 
	 * @Description: 验证当前活动关联的优惠券是否已经发放完毕
	 * @param activityId
	 *            活动Id
	 * @param cityNo
	 *            城市编号
	 * @return 1:优惠券已经发放结束 2:活动已结束
	 * @author CHEHUANBO
	 * @version V2.6.2
	 * 
	 */
	@Override
	public CouponStatus isReceiveCouponByActivityId(String activityId, String cityNo) {

		if (StringUtils.isBlank(activityId)) {
			log.error("验证当前活动关联的优惠券是否已经发放完毕被拒绝，原因：activityId is null or userId is null");
		}

		// 通过活动ID,获取所有活动关联的优惠券
		List<_Coupon> couponList = couponDao.getCouponByActivityIdToDb(activityId);

		if (couponList != null && couponList.size() > 0) {

			for (_Coupon coupon : couponList) {
				// 获取优惠券发放数量
				int couponGrantNumber = coupon.getNumber();
				// 从缓存中获取当前优惠券已发放数量
				long isGrantNumber = couponGrantRecordCacheDao
						.getCouponGrantRecordToCacheByCouponId(coupon.getCouponId());
				// 验证优惠券是否已经发放完成
				if (couponGrantNumber <= isGrantNumber) {
					return ActivityEnum.CouponStatus.couponGrantComplet;
				}
				// 验证优惠券是否已经失效
				if (DateFormatUtil.compareDate(coupon.getEndTime(), new Date()) == -1) {
					return ActivityEnum.CouponStatus.couponInvalid;
				}

				// 限制优惠券发放城市
				// if (coupon.getCityScope() == 2) {
				// // 获取优惠券关联城市集合
				// List<CouponCity> couponCityList =
				// couponCityCacheDao.getCouponCityToCache(coupon.getCouponId());
				// if (couponCityList != null && couponCityList.size() > 0) {
				// boolean isFlag = true;
				// for (CouponCity couponCity : couponCityList) {
				// if (couponCity.getCityNo() == cityNo) {
				// isFlag = false;
				// }
				// }
				// if (isFlag) {
				// return ActivityEnum.CouponStatus.couponGrantComplet;
				// }
				// }
				// }

				return ActivityEnum.CouponStatus.couponEffective;
			}
		}

		return ActivityEnum.CouponStatus.couponInvalid;

	}

	/**
	 * 
	 * @Description: 是否领取过优惠券
	 * @param userId
	 *            用户ID
	 * @param activityId
	 *            活动ID
	 * @return boolean true 已领过 false 未领过
	 * @author CHEHUANBO
	 * @version V2.6.2
	 * 
	 */
	@Override
	public boolean isGrantCoupon(String userId, String activityId) {

		CouponGrantRecord couponGrantRecord = couponGrantRecordDao.getCouponGrantRecordToDb(activityId, userId);

		if (couponGrantRecord != null) {
			return true;
		}
		return false;
	}

}
